'use strict';
module.exports = {
	/**
	 * 添加/取消收藏
	 * @url client/user/kh/collect 前端调用的url参数地址
	 * data 请求参数 说明
	 * @param {String} _id  收藏ID
	 * @param {Number} type 类型  1博客  2资源
	 * @param {String} status 1添加 2取消
	 * @param {String} title 标题（添加必传）
	 * @param {String} author_id  作者id（添加必传）
	 * @param {String} author_nickname 作者昵称（添加必传）
	 * @param {String} author_avatar 作者头像（添加必传）
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let { _id, type, title, author_id, author_nickname, author_avatar, status } = data;

		let dbName = "db-collect";
		
		let dbRes = await vk.baseDao.selects({
			dbName,
			getOne: true,
			getMain: true,
			whereJson: {
				collect_id: _id,
				uid: userInfo._id
			}
		})
		
		if(status === 1) {
			res["data"] = await vk.baseDao.add({
				dbName,
				dataJson: {
					collect_id: _id,
					type: type,
					title: title,
					author_id: author_id,
					author_nickname: author_nickname,
					author_avatar: author_avatar,
					uid: userInfo._id,
				}
			})
			
			if(type === 1) {
				let num = await vk.baseDao.update({
					dbName: "db-article",
					whereJson: {
						_id: _id
					},
					dataJson: {
						collect_num: _.inc(1)
					}
				})
			} else {
				let num = await vk.baseDao.update({
					dbName: "db-resource",
					whereJson: {
						_id: _id
					},
					dataJson: {
						collect_num: _.inc(1)
					}
				})
			}
		} else if(dbRes && status === 2) {
			res["data"] = await vk.baseDao.deleteById({
				dbName,
				id: dbRes._id
			})
			
			if(type === 1) {
				let num = await vk.baseDao.update({
					dbName: "db-article",
					whereJson: {
						_id: _id
					},
					dataJson: {
						collect_num: _.inc(-1)
					}
				})
			} else {
				let num = await vk.baseDao.update({
					dbName: "db-resource",
					whereJson: {
						_id: _id
					},
					dataJson: {
						collect_num: _.inc(-1)
					}
				})
			}
		} else {
			return { code: -1, msg: "Invalid status parameter"}
		}
		
		delete res["data"];
		
		res["msg"] = status !== 2? "收藏成功": "取消成功";
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
